package com.chenailin.www.service;

import com.chenailin.www.dao.ReportDAO;
import com.chenailin.www.daoimpl.ReportDAOImpl;
import com.chenailin.www.exception.ServiceException;
import com.chenailin.www.pojo.Doctor;
import com.chenailin.www.pojo.Report;

import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.sql.SQLException;
import java.time.LocalDate;
import java.util.List;

public class ReportService {

    private final DoctorService doctorService = new DoctorService();
    private final AppointmentService appointmentService = new AppointmentService();
    private final RatingService ratingService = new RatingService();
    private final ReportDAO reportDAO = new ReportDAOImpl();

    // 生成报表
    public void generateDailyReport() {
        LocalDate reportDate = LocalDate.now();
        String fileName = "report_daily_" + reportDate + ".csv";
        Path filePath = Paths.get("D:/code/cat/reports", fileName);

        try (BufferedWriter writer = Files.newBufferedWriter(filePath)) {
            // 写入CSV头部
            writer.write("医生ID,医生姓名,预约数量,平均评分\n");

            // 获取所有医生
            List<Doctor> doctors = doctorService.getAllDoctors();
            for (Doctor doctor : doctors) {
                // 获取当天预约数
                int appointmentCount = appointmentService.getDailyAppointments(doctor.getDocId(), reportDate);

                // 获取平均评分
                double avgRating = ratingService.calculateDoctorRating(doctor.getDocId());

                // 写入CSV行
                writer.write(String.format("%d,%s,%d,%.1f\n",
                        doctor.getDocId(),
                        doctor.getDocName(),
                        appointmentCount,
                        avgRating));
            }

            // 保存报表记录
            saveReportRecord(reportDate, filePath.toString());

            System.out.println("日报表生成成功: " + filePath);
        } catch (IOException e) {
            System.err.println("生成报表失败: " + e.getMessage());
        }
    }

    // 保存报表
    private void saveReportRecord(LocalDate date, String path) {
        Report report = new Report();
        report.setReportDate(date);
        report.setFilePath(path);
        try {
            if(reportDAO.addReportRecord(report)) {
                System.out.println("报表记录保存成功: " + report);
            }
        } catch (SQLException e) {
            throw new ServiceException("报表记录保存失败", e);
            // 可添加重试机制或日志记录
        }
    }

}
